var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var router = require('./router/router')
var cookieParser = require('cookie-parser');
var cors = require('cors');
var chat = require('./model/chat')
var app = express();

//连接socket.io
const server = require('http').Server(app);
const io = require('socket.io')(server);
io.on('connection',(socket)=>{
    //console.log('user login');
    socket.on('sendMsg',(data)=>{
        console.log(data);
        const {text,from,to} = data;
        const chatid = [from,to].sort().join('_');
        //console.log(chatid);
        //console.log(text,from,to);
        chat.create({chatid,from,to,content:text},(err,data)=>{
            //console.log(data);
            io.emit('receiveMsg',data);
        });
        
    })
})
//模板引擎
// app.engine('html', require('express-art-template'));

// 配置模板引擎和 body-parser 一定要在 app.use(router) 挂载路由之前
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());

app.use(cors({
    origin: true,
    credentials: true,
}));
app.use(cookieParser());

//静态资源
app.use('/node_modules/',express.static(path.join(__dirname,"./node_modules/")));
app.use('/public/',express.static(path.join(__dirname,"./public/")));
//运行跨域
// app.use(function (req, res, next) {
//     res.header("Access-Control-Allow-Origin", "*");
//     res.header("Access-Control-Allow-Headers", "X-Requested-With");
//     res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
//     next();
// });

app.use(router);


server.listen('3005',function () {
    console.log('server is running');
})